<?php
include_once("helpers.php");
// 定义宽高
$width = 80;
$height = 34;
// 创建画布
$result = imagecreatetruecolor($width, $height);
// 设置背景颜色,颜色必须使用rgb格式
$BgColor = imagecolorallocate($result, 238, 238, 238); //#eeeeee
// 绘制图片背景,把背景颜色加入图片
imagefilledrectangle($result, 0, 0, $width, $height, $BgColor);
// 设置文字颜色
$textColor = imagecolorallocate($result, 255, 0, 0); //#ff0000
// 字体文件 Windows要的是绝对路径
$FontPath = $_SERVER['DOCUMENT_ROOT'] . '/assets/fonts/OpenSans-Light.ttf';
// 生成随机字符
$code_1 = build_randstr(1);
$code_2 = build_randstr(1);
$code_3 = build_randstr(1);
$code_4 = build_randstr(1);
// 把字符加入画布
imagettftext($result, 16, mt_rand(-30, 30), 5, 26, $textColor, $FontPath, $code_1);
imagettftext($result, 16, mt_rand(-30, 30), 30, 26, $textColor, $FontPath, $code_2);
imagettftext($result, 16, mt_rand(-30, 30), 45, 26, $textColor, $FontPath, $code_3);
imagettftext($result, 16, mt_rand(-30, 30), 60, 26, $textColor, $FontPath, $code_4);
// 往里面加一些点
for ($i = 0; $i <= 10; $i++) {
  imagesetpixel($result, mt_rand(0, $width), mt_rand(0, $height), imagecolorallocate($result, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)));
}
// 往里面一些线
for ($i = 0; $i <= 5; $i++) {
  imageline($result, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), imagecolorallocate($result, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)));
}
// 开启会话session
session_start();
$_SESSION['code'] = $code_1 . $code_2 . $code_3 . $code_4;

// 设置请求头:告诉浏览器这是一张图片
header('Content-Type:image/png');
imagepng($result);
